package org.example.app.web;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import jakarta.annotation.Resource;
import org.example.app.common.enums.YesNo;
import org.example.app.common.model.JSONResponse;
import org.example.app.dao.model.User;
import org.example.app.dao.service.UserService;
import org.example.app.web.bo.UserBO;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.validation.Valid;

@RestController
@RequestMapping("/user")
public class UserController {

    @Resource
    private UserService userService;

    @GetMapping("/query")
    public JSONResponse<?> getUserById(@RequestParam(name = "id", required = false) Long id) {
        if (id == null) {
            return JSONResponse.error("id 不能为空");
        }

        User user = userService.getById(id);
        if (user == null) {
            return JSONResponse.error("用户不存在");
        }

        return JSONResponse.success(user);
    }

    @PostMapping("/register")
    public JSONResponse<?> updateUser(@Valid @RequestBody UserBO reqBO) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(User.COLUMNS.EMAIL.getColumn(), reqBO.getEmail());
        User user = userService.getOne(queryWrapper);
        if (user != null) {
            return JSONResponse.error("用户已注册");
        }

        user = new User();
        user.setName(reqBO.getName());
        user.setEmail(reqBO.getEmail());
        user.setPhone(reqBO.getPhone());
        user.setStatus(YesNo.NO.getValue());
        boolean success = userService.saveOrUpdate(user);
        if (success) {
            return JSONResponse.success(true);
        }

        return JSONResponse.error(false, "注册失败");
    }

}
